package com.ktjiaoyu.springsecuritydemo.handle;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String url;
    public MyAuthenticationSuccessHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // import org.springframework.security.core.userdetails.User;
        User user = (User)authentication.getPrincipal();
        System.out.println("名字：" + user.getUsername());
        // 密码出于安全原因，会显示null
        System.out.println("密码：" + user.getPassword());
        System.out.println("权限列表：" + user.getAuthorities());
// 默认登录成功后的处理器中是使用转发形式进行页面跳转
// 现在自定义的登录成功处理器中使用response.sendRedirect重定向进行页面跳转，如此可以跳转到站外链接
        response.sendRedirect(url);
    }
}
